package edu.cornell.cubooks.utils;

import org.apache.commons.lang.ArrayUtils;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationTrustResolver;
import org.springframework.security.AuthenticationTrustResolverImpl;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.context.SecurityContext;
import org.springframework.security.context.SecurityContextHolder;

import edu.cornell.cubooks.domain.User;
import edu.cornell.cubooks.domain.Role;

/**
 * Helper which allow for retrieving currently logged in user.
 * 
 * @author CUBooks team
 *
 */
public class CurrentUser {
	
	/**
	 * Returns currently logged in user.
	 * 
	 * @return User currently logged in user or null otherwise
	 */
	public static User getUser() {
		User user = null;
		if (!isAnonymous()) {
			user =  (User) ((SecurityContext) SecurityContextHolder.getContext()).getAuthentication().getPrincipal();
		}
		return user;
    }
	
	public static boolean isAnonymous() {
		AuthenticationTrustResolver resolver = new AuthenticationTrustResolverImpl();
	    SecurityContext ctx = SecurityContextHolder.getContext();
	    if (ctx != null) {
	    	Authentication auth = ctx.getAuthentication();
	        return resolver.isAnonymous(auth);
	    }
	    return true;
	}
	 
	public static boolean isBuyer() {
		User user = CurrentUser.getUser();
		 if (user != null) {
			 GrantedAuthority authority = new GrantedAuthorityImpl(Role.ROLE_BUYER_NAME);
			 return ArrayUtils.contains(user.getAuthorities(), authority);
		 }
		 return false;
	}
	 
	public static boolean isSeller() {
		User user = CurrentUser.getUser();
		if (user != null) {
			GrantedAuthority authority = new GrantedAuthorityImpl(Role.ROLE_SELLER_NAME);
			return ArrayUtils.contains(user.getAuthorities(), authority);
		}
		return false;
	}
	
	public static boolean isAdmin() {
		User user = CurrentUser.getUser();
		if (user != null) {
			GrantedAuthority authority = new GrantedAuthorityImpl(Role.ROLE_ADMIN_NAME);
			return ArrayUtils.contains(user.getAuthorities(), authority);
		}
		return false;
	}
}
